package com.daka.service.impl;

import com.daka.dao.WelfareMapper;
import com.daka.entity.Welfare;
import com.daka.entity.WelfareItem;
import com.daka.service.WelfareItemService;
import com.daka.service.WelfareService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author beliveli on 2016/3/31 0031.
 */
@Service("welfareService")
@SuppressWarnings("unused")
public class WelfareServiceImpl implements WelfareService {

    @Resource
    private WelfareMapper welfareMapper;

    @Resource
    private WelfareItemService welfareItemService;

    public Welfare selectById(Long id) {
        return welfareMapper.selectById(id);
    }

    public List<Welfare> selectAll() {
        return welfareMapper.selectAll();
    }

    public List<Welfare> selectByPage(String code ,Integer status, String name, Integer pageIndex, Integer pageSize) {
        return welfareMapper.selectByPage(code,status, name, pageIndex, pageSize);
    }

    public int selectCountByPage(String code ,Integer status, String name, Integer pageIndex, Integer pageSize) {
        return welfareMapper.selectCountByPage(code,status, name, pageIndex, pageSize);
    }

    public List<Welfare> selectByParam(String code, String key) {
        return welfareMapper.selectByParam(code, key);
    }

    public Welfare save(Welfare welfareParam) {

        int resultCount;
        if (null == welfareParam.getId() || welfareParam.getId() == 0) {
            welfareParam.setCreateTime(new Date());
            welfareParam.setStatus(0);
            welfareParam.setDelStatus(0);
            resultCount = welfareMapper.save(welfareParam);

            if ("0".equals(welfareParam.getCode())){

            }else if ("A".equals(welfareParam.getCode())){
                List<WelfareItem> itemList = new ArrayList<WelfareItem>();

                for (int i = 0; i < welfareParam.getAllCounts(); i++){
                    WelfareItem welfareItem = new WelfareItem();
                    welfareItem.setCode(welfareParam.getCode() + welfareParam.getId() + i);
                    welfareItem.setCreateTime(new Date());
                    welfareItem.setIsChanage(0);
                    welfareItem.setIsUse(0);
                    welfareItem.setWelfareId(welfareParam.getId());
                    itemList.add(welfareItem);
                }

                welfareItemService.insertBatch(itemList);
            }
        } else {
            resultCount = welfareMapper.updateById(welfareParam);
        }

        if (resultCount == 0) {
            return null;
        }
        return welfareParam;
    }

    public int updateById(Welfare welfare) {
        return welfareMapper.updateById(welfare);
    }
}

